package com.feinno.urcs.group.pc.task;

import com.feinno.rpc.channel.RpcFuture;
import com.feinno.rpc.client.RpcMethodStub;
import com.feinno.urcs.group.api.GroupMessageLogService;
import com.feinno.urcs.group.pctask.task.AndPcGroupMsgArgs;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import com.feinno.urcs.group.util.DateUtils;
import com.feinno.urcs.group.util.MSRPTextMsgParser;
import com.feinno.urcs.group.util.MsrpContent;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceSetter;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.rpc.LegacyRpcClient;
import org.helium.framework.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by honghao on 7/20/15.
 */
@TaskImplementation(event = GroupTaskEvents.GROUP_MESSAGE_TO_PC)
public class AndPcGroupMessageTask implements Task<AndPcGroupMsgArgs> {

	private Logger LOGGER = LoggerFactory.getLogger(AndPcGroupMessageTask.class);
	@FieldSetter("${PC_SERVER_RPC_SERVICE}")
	private LegacyRpcClient pcServerRpcClient;
	private String rpcMethodName = "RcsGroupMsgDelivered";
	@ServiceSetter
	private GroupMessageLogService groupMessageLogService;

	@Override
	public void processTask(AndPcGroupMsgArgs args) {
		try {
			LOGGER.info("AndPcGroupMessageTask.processTask , args : {}", args.toString());
			if (args.getTimeLen() > 0) {
//				int timelen = args.getTimeLen() / 1000;
				int timelen = args.getTimeLen();
				args.setTimeLen(timelen);
			}
			RpcMethodStub stub = pcServerRpcClient.getMethodStub(rpcMethodName);
			RpcFuture future = stub.invoke(args);
			future.addListener(ret -> {
				if (ret.getError() != null) {
					groupMessageLogService.andPcMessageDownstreamLog(args, 400, "andPc RPC error", DateUtils.getUTCNow());
					LOGGER.warn("AndPcGroupMessageTask args:{} occur error : {}", args, ret.getError());
				} else {
					groupMessageLogService.andPcMessageDownstreamLog(args, 200, "OK",DateUtils.getUTCNow());
					LOGGER.info("ok args=" + args.toJsonObject());
				}
			});
		} catch (Exception e) {
			groupMessageLogService.andPcMessageDownstreamLog(args, 500, "AndPc Task ERROR",DateUtils.getUTCNow());
			LOGGER.error("invoke RcsGroupMsgDelivered occur error : {}", e);

		}
	}
}
